package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasJyzxxImportJcxxEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasJyzxxImportJcxxService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.vo.excel.GasJyzxxImportJcxxExcel;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;



/**
 * 基本信息
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-07-20 15:23:52
 */
@Controller
@RequestMapping("/gas/jcxx")
@Slf4j
public class GasJyzxxImportJcxxController {
    @Autowired
    private GasJyzxxImportJcxxService gasJyzxxImportJcxxService;
    @Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private HttpSessionService httpSessionService;
	
	
    @Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
	
    @ApiOperation(value = "新增")
    @PostMapping("/add")
 //  @RequiresPermissions("gasJyzxxImportJcxx:add")
    @ResponseBody
    public DataResult add(@RequestBody GasJyzxxImportJcxxEntity gasJyzxxImportJcxx){
        gasJyzxxImportJcxxService.saveJcxx(gasJyzxxImportJcxx);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
 //  @RequiresPermissions("gasJyzxxImportJcxx:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids){
        gasJyzxxImportJcxxService.removeByIdsJcxx(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("/update")
 //   @RequiresPermissions("gasJyzxxImportJcxx:update")
    @ResponseBody
    public DataResult update(@RequestBody GasJyzxxImportJcxxEntity gasJyzxxImportJcxx){
        gasJyzxxImportJcxxService.updateByIdJcxx(gasJyzxxImportJcxx);
        return DataResult.success();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "查询分页数据")
    @PostMapping("/list")
 //   @RequiresPermissions("gasJyzxxImportJcxx:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody GasJyzxxImportJcxxEntity gasJyzxxImportJcxx){
        Page page = new Page(gasJyzxxImportJcxx.getPage(), gasJyzxxImportJcxx.getLimit());
        LambdaQueryWrapper<GasJyzxxImportJcxxEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        if(TsBqUtils.isNotNull(gasJyzxxImportJcxx.getJyzId())){
            queryWrapper.eq(GasJyzxxImportJcxxEntity::getJyzId, gasJyzxxImportJcxx.getJyzId());

        }else{
        	 return DataResult.fail("加油站ID为NULL");
        }
        
        IPage<GasJyzxxImportJcxxEntity> iPage = gasJyzxxImportJcxxService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }
    
    
    @ApiOperation(value = "导出模板")
	@PostMapping("/exportTemplate")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult exportTemplate(@RequestBody GasStationinfoEntity vo) {

    	
		String currentDeptId = httpSessionService.getCurrentDeptId();

		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 市局 
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
		}else{
			// 省局
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}

		List<GasStationinfoEntity> list = gasStationinfoService.list(queryWrapper);

		if (list.size() > 0) {
			List<GasJyzxxImportJcxxExcel> excelList = new ArrayList<>();
			for (GasStationinfoEntity entity : list) {

				GasJyzxxImportJcxxExcel cygxx = GasJyzxxImportJcxxExcel.builder()
						.name(entity.getName())
						.nsrmc("")
						.nsrsbh("")
						.sjscjydz("")
						.cpylsjypzzsYxqz("")
						.wxhxpjyxkzYxqz("")
						.zgqx("")
						.jyzwgZp("http://13.10.4.17:8001/files/gasphoto/")
						.xykwgZp("http://13.10.4.17:8001/files/gasphoto/")
						.cjr("")
						.cjsj("")
						.zgfj("")
						.sfzcyy("")
						.jyzId(entity.getId())
						.jyzSsswjg("")
						.jd("")
						.wd("")
						.build();
				
				excelList.add(cygxx);
			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, GasJyzxxImportJcxxExcel.class);
				sheet1.setSheetName("数据");
				writer.write(excelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);

				return DataResult.success(excelFileInfo);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return DataResult.fail("xlsx生成失败：" + e.toString());
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return DataResult.fail("xlsx生成失败：" + e.toString());
				}
			}
		} else {
			return DataResult.fail("传入的ids为null！");
		}
	}
	
	@ApiOperation(value = "导入数据")
	@PostMapping("/importData")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult importData(@RequestParam("file") MultipartFile[] files) {

		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {
				InputStream inputStream = null;
				try {
					inputStream = file.getInputStream();
					Sheet sheet = new Sheet(1, 1);
					List<Object> readList = EasyExcelFactory.read(inputStream, sheet);
					List<GasJyzxxImportJcxxEntity> jcxxList = new ArrayList<>();

					for (Object object : readList) {
						List<String> list = TsBqUtils.castList(object, String.class);
						
						String name = list.get(0); // (value = "加油站名称", index = 1)
						String nsrmc = list.get(1); // (value = "纳税人名称", index = 2)
						String nsrsbh = list.get(2); // (value = "纳税人识别号", index = 3)
						String sjscjydz = list.get(3); // (value = "实际生产经营地址", index = 4)
						String cpylsjypzzsYxqz = list.get(4); // (value = "成品油零售经营批准证书有效期止", index = 5)
						String wxhxpjyxkzYxqz = list.get(5); // (value = "危险化学品经营许可证有效期止", index = 6)
						String zgqx = list.get(6); // (value = "主管区县", index = 7)
						String jyzwgZp = list.get(7);// (value = "加油站外观图片", index = 8) 
						String xykwgZp = list.get(8); // (value = "卸油口外观图片", index = 9)
						String cjr = list.get(9); // (value = "采集人", index = 10)
						String cjsj = list.get(10); // (value = "采集时间", index = 11)
						String zgfj = list.get(11); // (value = "主管分局", index = 12)
						String sfzcyy = list.get(12); // (value = "是否正常运营", index = 13)
						String jyzId = list.get(13); // (value = "加油站ID", index = 14)
						String jyzSsswjg = list.get(14); // (value = "加油站-所属税务机关代码-维护字段", index = 15)
						String jd = list.get(15); 
						String wd = list.get(16); 
						
						log.info("正在处理加油站：" + name + ",ID:" + jyzId);
						if (TsBqUtils.isNull(jyzId)) {
							return DataResult.fail("表格中存在【加油站id】为空的！");
						}
						
						GasJyzxxImportJcxxEntity jcxx = new GasJyzxxImportJcxxEntity();
		                
						jcxx.setNsrmc(nsrmc); 
						jcxx.setNsrsbh(nsrsbh);
						jcxx.setSjscjydz(sjscjydz);
						jcxx.setCpylsjypzzsYxqz(cpylsjypzzsYxqz);
						jcxx.setWxhxpjyxkzYxqz(wxhxpjyxkzYxqz);
						jcxx.setZgqx(zgqx);
						jcxx.setJyzwgZp(jyzwgZp); 
						jcxx.setXykwgZp(xykwgZp);
						jcxx.setCjr(cjr);
						jcxx.setCjsj(cjsj); 
						jcxx.setZgfj(zgfj);
						jcxx.setSfzcyy(sfzcyy);
						jcxx.setJyzId(jyzId);
						jcxx.setJyzSsswjg(jyzSsswjg); 
						jcxx.setJd(jd);
						jcxx.setWd(wd);
						
						jcxxList.add(jcxx);
					}
					
					for (GasJyzxxImportJcxxEntity entity : jcxxList) {
						gasJyzxxImportJcxxService.saveJcxx(entity);
					}

				} catch (Exception e) {
					log.error("importData" + e.getMessage());
					
				} finally {
					if (inputStream != null) {
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
							return DataResult.fail(e.getMessage());
						}
					}
				}
			}
		}

		return DataResult.success();
	}
	
	
}
